/*
 * @Author: fantasy 
 * @Date: 2021-08-20 14:57:00 
 * @Last Modified by: fantasy
 * @Last Modified time: 2021-09-08 10:17:18
 * 首页
 */
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tvTest/inherited_page.dart';

class Home extends StatefulWidget {
  const Home({Key key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
  ///图片菜单数据
  List imgArr = [
    'assets/hmjz.jpg',
    'assets/zqc.jpg',
    'assets/lifeandpi.jpg',
    'assets/zzx.jpg',
    'assets/mgdz.jpg',
  ];

  List numsPad = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'];

  String pidStr = '';

  FocusNode node1 = FocusNode();
  FocusNode node2 = FocusNode();
  FocusNode node3 = FocusNode();
  FocusNode node4 = FocusNode();
  FocusNode node5 = FocusNode();
  FocusNode node6 = FocusNode();

  AnimationController _controller;
  final controller = TextEditingController();

  String selectedImage = '';

  int count = 0;

  List<SnowFlake> snows = List.generate(80, (_) {
    return SnowFlake();
  });

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // Future.delayed(Duration(seconds: 1), () {
    //   showAlertDialogSetting();
    // });
    _controller = AnimationController(
      duration: Duration(seconds: 3),
      vsync: this,
    )..repeat(reverse: false);
  }

  @override
  void dispose() {
    _controller.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('QQ音乐'),
          centerTitle: true,
          elevation: 0.0,
        ),
        backgroundColor: Colors.blueGrey,
        body: Container(
          child: Row(
            children: [
              Container(
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                          colors: [Colors.blue, Colors.lightBlue, Colors.white],
                          end: Alignment.bottomCenter,
                          begin: Alignment.topCenter)),
                  width: 180,
                  child: Column(children: [
                    Container(
                      margin: EdgeInsets.only(
                        top: 20,
                      ),
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              margin: EdgeInsets.only(right: 10),
                              child: Icon(
                                Icons.music_video_outlined,
                                color: Colors.green,
                                size: 32,
                              ),
                            ),
                            Container(
                              child: Text('QQ音乐',
                                  style: TextStyle(
                                      color: Colors.lightGreenAccent,
                                      fontSize: 26,
                                      fontWeight: FontWeight.bold)),
                            )
                          ]),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 16, bottom: 20),
                      child: Text('在线音乐',
                          style:
                              TextStyle(color: Colors.black45, fontSize: 18)),
                    ),
                    Expanded(
                      flex: 1,
                      child: AnimatedBuilder(
                        animation: _controller,
                        builder: (BuildContext context, Widget child) {
                          return CustomPaint(
                            painter: MyPaint(snows),
                          );
                        },
                      ),
                    ),
                  ])),
              Expanded(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                    ClipPath(
                      clipper: MyCliper(),
                      child: Container(
                        height: 80,
                        color: Colors.blueGrey[300],
                      ),
                    ),
                    SizedBox(height: 30),
                    Row(children: [
                      SizedBox(width: 10),
                      singleImageMenu(240, 240, imgArr[0], node: node1),
                      Column(children: [
                        singleImageMenu(240, 110, imgArr[1], node: node2),
                        singleImageMenu(240, 110, imgArr[2], node: node3),
                      ]),
                      Column(children: [
                        singleImageMenu(240, 110, imgArr[3], node: node4),
                        singleImageMenu(240, 110, imgArr[4], node: node5),
                      ])
                    ]),
                    SizedBox(height: 30),
                    Row(children: [
                      SizedBox(width: 20),
                      RotationTransition(
                        turns: Tween(begin: 0.0, end: 1.0)
                            .chain(CurveTween(curve: Interval(0.0, 0.25)))
                            .animate(_controller),
                        child: Container(
                          child: Icon(
                            Icons.book_online_outlined,
                            size: 40,
                          ),
                        ),
                      ),
                      SizedBox(width: 20),
                      ScaleTransition(
                        scale: Tween(begin: 0.5, end: 1.0)
                            .chain(CurveTween(curve: Interval(0.25, 0.5)))
                            .animate(_controller),
                        child: ClipOval(
                          child: Container(
                              width: 50, height: 50, color: Colors.greenAccent),
                        ),
                      ),
                      SizedBox(width: 20),
                      FadeTransition(
                        opacity: Tween(begin: 0.1, end: 1.0)
                            .chain(CurveTween(curve: Interval(0.5, 0.75)))
                            .animate(_controller),
                        child: Container(
                          child: Icon(
                            Icons.phone_iphone_outlined,
                            color: Colors.blue[900],
                            size: 40,
                          ),
                        ),
                      ),
                      SizedBox(width: 20),
                      SlideTransition(
                        position: Tween(begin: Offset.zero, end: Offset(0.8, 0))
                            .chain(CurveTween(curve: Interval(0.75, 1.0)))
                            .chain(CurveTween(curve: Curves.bounceInOut))
                            .animate(_controller),
                        child: Icon(Icons.android_outlined,
                            color: Colors.red, size: 40),
                      ),
                      SizedBox(width: 60),
                      InheritedWidgetTestRoute(),
                    ]),
                  ]))
            ],
          ),
        ));
  }

  showAlertDialogSetting() {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return new AlertDialog(
          title: Text('设置项目ID'),
          content: StatefulBuilder(builder: (context, updateState) {
            return ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 180, maxWidth: 380),
                child: Column(children: [
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: 25,
                      vertical: 10,
                    ),
                    child: Container(
                      height: 40,
                      child: Text(pidStr),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(4),
                        border: Border.all(
                          width: 1.0,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ),
                  Wrap(
                      spacing: 5,
                      runSpacing: 2.0,
                      alignment: WrapAlignment.center,
                      children: numsPad.map((item) {
                        return FlatButton(
                          padding: EdgeInsets.zero,
                          focusColor: Colors.blue,
                          child: Container(
                              width: 76,
                              height: 26,
                              alignment: Alignment.center,
                              color: Colors.grey[200],
                              child: Text(
                                item,
                                style: TextStyle(fontSize: 18),
                              )),
                          onPressed: () {
                            if (item.toString() != '-') {
                              updateState(() {
                                pidStr = pidStr + item.toString();
                              });
                            } else {
                              if (pidStr.isNotEmpty) {
                                updateState(() {
                                  pidStr =
                                      pidStr.substring(0, pidStr.length - 1);
                                });
                              }
                            }
                            print('hahahhaha$pidStr');
                          },
                        );
                      }).toList())
                ]));
          }),
          actions: <Widget>[
            // RawKeyboardListener(
            //     onKey: (RawKeyEvent event) {
            //       // TODO: Key event here
            //       print('测试测试$event');
            //     },
            //     focusNode: FocusNode(),
            //     child: Container(
            //       child: new Text(
            //         '测试',
            //         style: TextStyle(fontSize: 18),
            //       ),
            //     )),
            new FlatButton(
              focusColor: Colors.green,
              child: new Text(
                '确定',
                style: TextStyle(fontSize: 18),
              ),
              onPressed: () {
                print('得到用户输入的项目ID$pidStr');
                // Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  /// 返回单个图片选项
  Widget singleImageMenu(double w, double h, String imageUrl,
      {FocusNode node}) {
    return FlatButton(
        focusColor: Colors.green,
        onPressed: () {
          setState(() {
            selectedImage = imageUrl;
          });
        },
        padding: EdgeInsets.zero,
        child: Container(
          width: w,
          height: h,
          margin: EdgeInsets.all(5),
          padding: EdgeInsets.all(8),
          decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                    spreadRadius: 1, blurRadius: 10, color: Colors.white38)
              ],
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                  width: 2,
                  color: selectedImage == imageUrl
                      ? Colors.yellow
                      : Colors.transparent)),
          child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.asset(
                imageUrl,
                fit: BoxFit.cover,
              )),
        ));
  }
}

class InheritedWidgetTestRoute extends StatefulWidget {
  @override
  _InheritedWidgetTestRouteState createState() =>
      _InheritedWidgetTestRouteState();
}

class _InheritedWidgetTestRouteState extends State<InheritedWidgetTestRoute> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: InheritedPage(
        //使用ShareDataWidget
        data: count,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(bottom: 20.0),
              child: _TestWidget(), //子widget中依赖ShareDataWidget
            ),
            RaisedButton(
              color: Theme.of(context).primaryColor,
              child: Text("Increment"),
              //每点击一次，将count自增，然后重新build,ShareDataWidget的data将被更新
              onPressed: () => setState(() => ++count),
            )
          ],
        ),
      ),
    );
  }
}

class _TestWidget extends StatefulWidget {
  @override
  __TestWidgetState createState() => __TestWidgetState();
}

class __TestWidgetState extends State<_TestWidget> {
  @override
  Widget build(BuildContext context) {
    //使用InheritedWidget中的共享数据
    return Text(InheritedPage.of(context).data.toString());
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    print("Dependencies change");
  }
}

class MyCliper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    var path = Path();
    path.lineTo(0, 0);
    path.lineTo(0, size.height);
    path.quadraticBezierTo(
        size.width / 4, size.height / 2 - 40, size.width / 2, size.height / 2);
    path.quadraticBezierTo(
        size.width / 4 * 3, size.height, size.width, size.height / 2);
    path.lineTo(size.width, size.height / 2);
    path.lineTo(size.width, 0);
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper oldClipper) {
    return false;
  }
}

class MyPaint extends CustomPainter {
  final wpaint = Paint()..color = Colors.white;
  final List<SnowFlake> snows;

  MyPaint(this.snows);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawCircle(size.center(Offset.zero), 30, wpaint);
    canvas.drawCircle(
        size.center(Offset(-10, -10)), 5, Paint()..color = Colors.black87);
    canvas.drawCircle(
        size.center(Offset(10, -10)), 5, Paint()..color = Colors.black87);

    canvas.drawArc(
        Rect.fromCircle(center: size.center(Offset(0, 0)), radius: 12),
        3.14 / 3,
        3.14 / 3,
        false,
        Paint()
          ..color = Colors.red
          ..strokeCap = StrokeCap.round
          ..strokeWidth = 5.0
          ..style = PaintingStyle.stroke);
    canvas.drawOval(
        Rect.fromCenter(
            center: size.center(Offset(0, 70)), width: 100, height: 110),
        wpaint);
    snows.forEach((element) {
      //每次刷新的时候执行fall函数,得到每个雪花的位置
      element.fall();
      canvas.drawCircle(Offset(element.x, element.y), element.radius, wpaint);
    });
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

//单个雪花显示
class SnowFlake {
  double x = Random().nextDouble() * 180 - 100;
  double y = Random().nextDouble() * 300;
  double radius = Random().nextDouble() * 2 + 2;
  double speed = Random().nextDouble() * 3 + 1;
  fall() {
    y = y + speed;
    if (y > 300) {
      y = 0;
      x = Random().nextDouble() * 180 - 100;
      radius = Random().nextDouble() * 2 + 2;
      speed = Random().nextDouble() * 3 + 1;
    }
  }
}

/**
 * //  建立连接
  _connect() async {
    String server = "your server name";
    int port = 1883;
    String clientId = "86-1885999fuehxz5f3ced1e";
    String userName = "86-18859995315";
    String password = "63ab9508485e131f946ce59ab9b3b687";
    MqttTool.getInstance()
        .connect(server, port, clientId, userName, password)
        .then((v) {
      if (v.returnCode == MqttConnectReturnCode.connectionAccepted) {
        print("恭喜你~ ====mqtt连接成功");
      } else if (v.returnCode == MqttConnectReturnCode.badUsernameOrPassword) {
        print("有事做了~ ====mqtt连接失败 --密码错误!!!");
      } else {
        print("有事做了~ ====mqtt连接失败!!!");
      }
    });
  }

//  订阅主题
  _subscribeTopic() {
    String clientId = "86-1885999fuehxz5f3ced1e";

    String topic = "device/F4CFA26F1E43/#";

    String topic2 = "reply/device/F4CFA26F1E43/#";
    MqttTool.getInstance().subscribeMessage(topic);
    MqttTool.getInstance().subscribeMessage(topic2);
  }
  
//  取消订阅
  _unSubscribeTopic() {
    String clientId = "86-1885999fuehxz5f3ced1e";
    String topic = "device/F4CFA26F1E43/#";
    MqttTool.getInstance().unsubscribeMessage(topic);
  }
  
//  发布消息
  _publishTopic() {
    String topic1 =
        "api/device/F4CFA26F1E43/86-1885999mvqqyy5f3cf0d5/attribute/OccupiedCoolingSetpoint";
    String str1 = "2950";

    String topic2 =
        "api/device/F4CFA26F1E43/86-1885999mvqqyy5f3cf0d5/attribute/OccupiedHeatingSetpoint";
    String str2 = "2900";
    MqttTool.getInstance().publishMessage(topic1, str1);
    MqttTool.getInstance().publishMessage(topic2, str2);
  }
  
//  监听消息的具体实现
  _onData(List<MqttReceivedMessage<MqttMessage>> data) {
    final MqttPublishMessage recMess = data[0].payload;
    final String topic = data[0].topic;
    final String pt = Utf8Decoder().convert(recMess.payload.message);
    String desString = "topic is <$topic>, payload is <-- $pt -->";
    print("string =$desString");
    Map p = Map();
    p["topic"] = topic;
    p["type"] = "string";
    p["payload"] = pt;
    ListEventBus.getDefault().post(p);
  }

//  开启监听消息
  _startListen() {
    _listenSubscription = MqttTool.getInstance().updates().listen(_onData);
  }
  
//  断开连接
  _disconnect() {
    MqttTool.getInstance().disconnect();
  }
 */
